package com.ruoyi.oss.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.oss.domain.SysOss;
import com.ruoyi.oss.domain.bo.SysOssDownloadRecordsSearchBo;
import com.ruoyi.oss.domain.bo.SysOssSearchListBo;
import com.ruoyi.oss.domain.vo.OssUploadResult;
import com.ruoyi.oss.domain.vo.SysOssDownloadRecordsVo;
import com.ruoyi.oss.service.SysOssDownloadRecordsService;
import com.ruoyi.oss.service.SysOssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * OSS云存储控制器
 *
 * @author xueyu
 */
@Api(value = "OSS云存储控制器", tags = "OSS云存储控制器")
@Slf4j
@RestController
@RequestMapping(value = "/system/oss")
public class SysOssController extends BaseController {


    private SysOssService sysOssService;
    private SysOssDownloadRecordsService sysOssDownloadRecordsService;

    @Autowired
    public void setSysOssDownloadRecordsService(SysOssDownloadRecordsService sysOssDownloadRecordsService) {
        this.sysOssDownloadRecordsService = sysOssDownloadRecordsService;
    }

    @Autowired
    public void setSysOssService(SysOssService sysOssService) {
        this.sysOssService = sysOssService;
    }

    /**
     * 查询文件上传记录 根据搜索条件
     *
     * @param searchBo 搜索条件
     * @return 文件上传记录集合  ajax
     */
    @ApiOperation(value = "分页查询文件上传记录")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public TableDataInfo<SysOss> queryList(SysOssSearchListBo searchBo) {
        PageDomain pageDomain = buildPageRequest();
        Page<SysOss> page = sysOssService.pageList(searchBo, pageDomain);
        return getDataTablePlus(page);
    }

    /**
     * 查看下载记录
     *
     * @param searchBo 查询参数
     * @return ajax
     */
    @ApiOperation(value = "查询下载记录列表")
    @RequestMapping(value = "queryDownloadRecordsList", method = RequestMethod.GET)
    public TableDataInfo<SysOssDownloadRecordsVo> queryDownloadRecordsList(SysOssDownloadRecordsSearchBo searchBo) {
        PageDomain pageDomain = buildPageRequest();
        Page<SysOssDownloadRecordsVo> page = sysOssDownloadRecordsService.pageList(searchBo, pageDomain);
        return getDataTablePlus(page);
    }

    /**
     * 上传OOS文件
     *
     * @param multipartFile 多部份文件上传
     * @return oss文件上传结果 ajax
     */
    @ApiOperation(value = "上传OSS文件")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @RepeatSubmit
    public R<OssUploadResult> upload(@RequestParam(value = "file") MultipartFile multipartFile) {
        if (multipartFile.isEmpty()) {
            return R.fail("上传文件不能为空!");
        }
        SysOss oss = sysOssService.upload(multipartFile);
        return R.ok(new OssUploadResult(oss));
    }

    /**
     * 文件下载
     *
     * @param id 文件上传记录的id
     * @return 文件
     */
    @ApiOperation(value = "文件下载")
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public ResponseEntity<StreamingResponseBody> download(@RequestParam(value = "id") Long id,
                                                          HttpServletRequest httpServletRequest,
                                                          HttpServletResponse httpServletResponse) {
        if (Objects.isNull(id)) {
            log.error("文件不能为空!");
            return ResponseEntity.notFound().build();
        }
        SysOss sysOss = sysOssService.findById(id);
        if (Objects.isNull(sysOss)) {
            log.error("没有根据ID:{}找到相关的OSS文件上传记录", id);
            return ResponseEntity.notFound().build();
        }
        try {
            return sysOssService.download(sysOss, httpServletRequest, httpServletResponse);
        } catch (Exception e) {
            log.error("", e);
            httpServletResponse.reset();
            httpServletResponse.setCharacterEncoding("utf-8");
            return ResponseEntity
                    .status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .contentType(MediaType.TEXT_PLAIN)
                    .body(o -> {
                        String errorMessage = "下载文件出现异常,请稍后重试或者联系管理员!";
                        o.write(errorMessage.getBytes(StandardCharsets.UTF_8));
                    });
        }
    }
}
